
package com.yishe.context;

import com.yishe.api.RestCodeConstants;
import com.yishe.helper.StringHelper;

import java.util.HashMap;
import java.util.Map;


public class BaseContextHandler {
	public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

	public static void set(String key, Object value) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			threadLocal.set(map);
		}
		map.put(key, value);
	}

	public static Object get(String key) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			threadLocal.set(map);
		}
		return map.get(key);
	}

	/**
	 * 获取：用户登录表的主键ID
	 * 
	 * @return
	 */
	public static String getUserID() {
		Object value = get(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_ID);
		return returnObjectValue(value);
	}

	/**
	 * 获取：用户登录名
	 * 
	 * @return
	 */
	public static String getUserCode() {
		Object value = get(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_CODE);
		return StringHelper.getObjectValue(value);
	}

	/**
	 * 获取：登录用户中文名称
	 * 
	 * @return
	 */
	public static String getUserName() {
		Object value = get(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_NAME);
		return returnObjectValue(value);
	}

	public static String getToken() {
		Object value = get(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_TOKEN);
		return StringHelper.getObjectValue(value);
	}

	/**
	 * 用户登录表的主键ID
	 * 
	 * @param userID 主键ID
	 */
	public static void setUserID(Integer userID) {
		set(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_ID, userID);
	}

	/**
	 * 用户登录名
	 * 
	 * @param userCode 登录ID
	 */
	public static void setUserCode(String userCode) {
		set(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_CODE, userCode);
	}

	/**
	 * 登录用户中文名称
	 * 
	 * @param userName
	 */
	public static void setUserName(String userName) {
		set(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_NAME, userName);
	}

	/**
	 * 登录token信息
	 * 
	 * @param token
	 */
	public static void setToken(String token) {
		set(RestCodeConstants.CommonConstants.CONTEXT_KEY_USER_TOKEN, token);
	}

	private static String returnObjectValue(Object value) {
		return value == null ? null : value.toString();
	}

	public static void remove() {
		threadLocal.remove();
	}

}
